package com.health.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.health.system.annotation.Log;
import com.health.system.common.result.Result;
import com.health.system.common.utils.CaptchaUtil;
import com.health.system.common.utils.ServletRequestUtil;
import com.health.system.constant.SecurityConstant;
import com.health.system.entity.UserAuth;
import com.health.system.entity.UserInfo;
import com.health.system.mapper.RoleMapper;
import com.health.system.mapper.UserAuthMapper;
import com.health.system.service.UserInfoService;
import com.health.system.vo.RegisterVo;
import com.pig4cloud.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import static com.health.system.constant.LogTypeConstant.INSERT;


@Validated
@Api(tags = "登录模块")
@RestController
public class LoginController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserAuthMapper userAuthMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Log(INSERT)
    @ApiOperation("生成验证码图片")
    @PostMapping("/captcha")
    public Result<String> createCaptcha() {
        ArithmeticCaptcha captcha = CaptchaUtil.createCaptcha();

        ServletRequestUtil.getHttpSession().setAttribute(SecurityConstant.CAPTCHA_KEY, captcha.text());

        return Result.ok(captcha.toBase64());
    }

    @ApiOperation("注册账号")
    @PostMapping("/register")
    public Result<String> register(@RequestBody RegisterVo vo) throws Exception {
        UserAuth userAuth = userAuthMapper.selectOne(new LambdaQueryWrapper<UserAuth>().eq(UserAuth::getUsername, vo.getUsername()));
        if (userAuth != null) {
            throw new Exception("账号已存在");
        }
        UserInfo userInfo = UserInfo.builder().build();
        userInfoService.save(userInfo);

        UserAuth auth = UserAuth.builder()
                .userInfoId(userInfo.getId())
                .ipSource("本地")
                .ipAddress("127.0.0.1")
                .username(vo.getUsername())
                .password("{noop}" + vo.getPassword())
                .build();
        userAuthMapper.insert(auth);

        userInfo.setNickname(vo.getUsername());
        userInfo.setUserId(auth.getId());
        userInfoService.updateById(userInfo);

        roleMapper.insertRelationUser(1L, auth.getId());

        return Result.ok();
    }
}
